<?php
declare(strict_types=1);

namespace Service\GoodsService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsClass;
use App\Model\BbcModel\GoodsBrand;
use Service\GoodsClassService\ClassService;
use Service\CountryService\CountryService;
use Service\GoodsBrandService\BrandService;
use Service\HelperService\Common;
use Hyperf\DbConnection\Db;

/**
 * TO C/B SBBC 商品品牌
 * @author hj
 */
class GoodsBrandService extends BaseService
{
    /**
     * 品牌列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function brandList(array $param)
    {
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        $model = GoodsBrand::where('df', 0)->where('cid', (int)($param['cid']));
        if (isset($param['class_id']) && !empty($param['class_id']) && (preg_match("/^[1-9]\d*$/", (string)$param['class_id']) == 1)) {
            $class_id  = (int)($param['class_id']);
            $clasRes   = ClassService::getClassChildren($class_id);
            $class_ids = $clasRes['code'] == Normal::SUC ? array_column($clasRes['data'], 'id') : [];
            array_push($class_ids, $class_id);
            if (!empty($class_ids)) {
                $model = $model->whereIn('class_id', $class_ids);
            }
        }
        $fields = ['id', 'country_id', 'name', 'pic'];
        $result = $model->select($fields)->orderByRaw('sort desc, id desc')->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功');
        }
        $collection = $result->getCollection();
        $countrys   = CountryService::getCountry();
        $collection->each(function ($item, $key) use ($countrys) {
            $country            = $countrys[$item->country_id] ?? [];
            $item->country_name = !empty($country['name']) ? $country['name'] : '';
            $country_icon       = !empty($country['icon']) ? $country['icon'] : '';
            if (!empty($country_icon) && strpos($country_icon, 'http') === false) {
                $item->country_icon = Common::$pre_image_url . $country_icon;
            } else {
                $item->country_icon = '';
            }
            if (!empty($item->pic) && strpos($item->pic, 'http') === false) {
                $item->pic = Common::$pre_image_url . $item->pic;
            }
            if (strpos($item->name, '其他') !== false) {
                $item->name         = '';
                $item->country_name = '';
                $item->country_icon = '';
            }
            $item->isChina = $item->country_name == '中国' ? 1 : 0;
            return $item;
        });
        return Normal::returnCode(Normal::SUC, '获取成功', $collection->toArray());
    }

    /**
     * 查询品牌信息以及品牌所属商品，以及这些商品的所属分类
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getInfo(array $param)
    {
        if (!isset($param['brand_id']) || empty($param['brand_id']) || (preg_match("/^[1-9]\d*$/", (string)$param['brand_id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument brand_id');
        }
        $param['brand_id'] = (int)($param['brand_id']);
        $brand = BrandService::getBrand([$param['brand_id']]);
        if (!$brand || !isset($brand[$param['brand_id']])) {
            return Normal::returnCode(Normal::FAIL, '品牌不存在');
        }
        $result['info']  = $brand[$param['brand_id']];
        $result['class'] = [];
        $class_ids       = Goods::where('brand_id', $param['brand_id'])->groupBy('class_id')->pluck('class_id')->toArray();
        if ($class_ids) {
            $class = GoodsClass::whereIn('id', $class_ids)->select(['id', 'name'])->get()->toArray();
            if ($class) {
                $result['class'] = $class;
            }
        }
        return Normal::returnCode(Normal::SUC, '获取成功', $result);
    }

    /**
     * 获取list
     * @param array $ids
     */
    public function getBrandList(array $ids)
    {
        return Db::table('ly_goods_brand')
            ->select([
                'ly_goods_brand.*',
                'ly_country.icon as icon',
                'ly_country.bgcolor_code',
                'ly_country.country_logo',
                'ly_country.name as country_name',
                'ly_country.short_name as country_short_name',
                'ly_brand_layout_image.cover_image as layout_cover_image',
                'ly_brand_layout_image.tool_logo as layout_cover_tool_logo',
                'ly_brand_layout_image.tool_background_img as layout_tool_background_img',
                'ly_brand_layout_image.slogan as layout_slogan',
            ])
            ->leftJoin('ly_country',"ly_country.id","=","ly_goods_brand.country_id")
            ->leftJoin('ly_brand_layout_image',"ly_brand_layout_image.brand_id","=","ly_goods_brand.id")
            ->where(['ly_goods_brand.df'=>0,'ly_brand_layout_image.cid'=>'ly_goods_brand.cid'])
            ->whereIn('ly_goods_brand.id',$ids)
            ->get()->toArray();
    }
}